package com.heima.common.delayTask;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisDelayedQueueUtil {

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 把元素放入延迟队列
     * 使用zset  list
     * @param t  延迟的元素
     * @param queueName  队列的名字
     * @param delaytime  延迟的时间
     * @param timeUnit 时间单位
     * @param <T>
     */
    public <T> void addToQueue(T t,String queueName,Long delaytime,TimeUnit timeUnit){
//        声名阻塞队列
        RBlockingDeque<T> blockingDeque = redissonClient.getBlockingDeque(queueName);
//        声名延迟队列
        RDelayedQueue<T> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
//        放入延迟元素
        delayedQueue.offer(t,delaytime,timeUnit);
        log.info("添加延迟队列名：{}，值：{}，延迟时间：{}",queueName,t,delaytime);
    }

    /**
     * 从队列获取延迟元素
     * @param queueName
     * @param <T>
     * @return
     */
    public <T> T getFromQueue(String queueName) throws InterruptedException {
        RBlockingDeque<T> blockingDeque = redissonClient.getBlockingDeque(queueName);
        T take = blockingDeque.take();
        log.info("从延迟队列获取元素，t={}",take);
        return take;
    }

    /**
     * 从队列中删除元素
     * @param queueName
     * @param t
     * @param <T>
     */
    public <T> void removeFromQueye(String queueName,T t){
//        声名阻塞队列
        RBlockingDeque<T> blockingDeque = redissonClient.getBlockingDeque(queueName);
//        声名延迟队列
        RDelayedQueue<T> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
//        删除元素
        delayedQueue.remove(t);
        log.info("删除延迟元素，t={}",t);
    }

}
